import { defineStore } from 'pinia'
import { getStore, setStore } from 'src/utils/storage'

const compareTag = (target = {}, tag = {}) => {
  if (target.path !== tag.path) return false
  return target.menuId === tag.menuId
}

export const tagsStores = defineStore('tagsStores', {
  state: () => ({
    tags: getStore('tags') || []
  }),
  getters: {},
  actions: {
    SET_TAGS (tags = [], addInitTag) {
      if (addInitTag) this.tags = [...tags]
      else this.tags = tags

      setStore('tags', this.tags)
    },

    ADD_TAG (tag) {
      if (this.tags.findIndex(el => compareTag(el, tag)) !== -1) return

      this.tags.push(tag)
      this.SET_TAGS(this.tags)
    },

    REMOVE_TAGS (payload) {
      switch (typeof payload) {
        case 'undefined':
          this.SET_TAGS()
          break
        case 'object':
          if (payload.side === 'left') {
            this.SET_TAGS(this.tags.filter((el, i) => i >= payload.index), true)
          } else if (payload.side === 'right') {
            this.SET_TAGS(this.tags.filter((el, i) => i <= payload.index))
          } else {
            this.SET_TAGS(this.tags.filter((el, i) => i === payload.index), payload.index !== 0)
          }
          break
        default:
          this.SET_TAGS(this.tags.filter((el, i) => i !== payload))
      }
    }
  }
})